package com.example.graduatetest.activitys;

import static com.example.graduatetest.utils.Constant.getBytesByBitmap;

import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProviders;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;

import com.example.graduatetest.R;
import com.example.graduatetest.bean.Classes;
import com.example.graduatetest.bean.User;
import com.example.graduatetest.databinding.ActivityClassDetailBinding;
import com.example.graduatetest.utils.Base64Util;
import com.example.graduatetest.utils.Constant;
import com.example.graduatetest.utils.GsonUtils;
import com.example.graduatetest.utils.HttpUtil;
import com.example.graduatetest.view.model.ClassDetailViewModel;

import java.util.HashMap;
import java.util.Map;

public class ClassDetailActivity extends AppCompatActivity {
    private ActivityClassDetailBinding binding;
    private ClassDetailViewModel classDetailViewModel;
    //定义返回值，判断图片的来源
    private int Photo_ALBUM = 1, CAMERA = 2;
    //定义图片的路径
    private String imagePath = null;
    int FLAG = 0;
    //bitmap对象
    private Bitmap bp = null;
    //更新子线程
    private Handler handler = new Handler();
    private String IDs = "jk111",names="zhang";
    private Classes ownClass;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_class_detail);
        //隐藏ActionBar
        if(getSupportActionBar() != null){
            ActionBar actionBar = getSupportActionBar();
            actionBar.hide();
        }
        binding = DataBindingUtil.setContentView(this,R.layout.activity_class_detail);

        //接受Intent传来的数据
        Intent intent = getIntent();
        ownClass = (Classes) intent.getSerializableExtra("classes");

        //LiveData
        classDetailViewModel = ViewModelProviders.of(this).get(ClassDetailViewModel.class);
        binding.setClassDetailViewModel(classDetailViewModel);
        binding.setLifecycleOwner(this);
        classDetailViewModel.init(this,binding,ownClass);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // 相册选择图片
        if (requestCode == Photo_ALBUM) {
            if (data != null) {
                Uri uri = data.getData();
                Cursor cursor = getContentResolver().query(uri, null, null, null, null);
                cursor.moveToNext();

                //获得图片的绝对路径
                imagePath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA));
                cursor.close();
                Log.i("图片路径", imagePath);
                bp = Constant.getImage(imagePath);
                runThread(this);
            }
        } else if (requestCode == CAMERA) {
            imagePath = classDetailViewModel.getImagePath();
            bp = Constant.getImage(imagePath);
            runThread(this);
        }
    }


    void runThread(final Activity activity) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String url = Constant.ADDURL;
                byte[] bytes1 = getBytesByBitmap(bp);
                //   byte[] bytes1 = FileUtil.readFileByBytes(imagePath);
                String image1 = Base64Util.encode(bytes1);
                User user = Constant.checkStudentOrTeacher(activity);

                try {
                    Map<String, Object> map = new HashMap<>();
                    map.put("image", image1);
                    map.put("group_id", ownClass.getId());
                    map.put("user_id", user.getNumber());
                    map.put("user_info", "classId:"+ownClass.getId()+",studentNumber:"+user.getNumber());
                    map.put("liveness_control", "NORMAL");
                    map.put("image_type", "BASE64");
                    map.put("quality_control", "LOW");

                    String param = GsonUtils.toJson(map);

                    // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。

                    String accessToken = Constant.getAuth(Constant.clientId,Constant.clientSecret);

                    String result = HttpUtil.post(url, accessToken, "application/json", param);
                    if(result.contains("SUCCESS")){
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(activity, "上传人脸成功", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }else{
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(activity, "上传人脸失败", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }



}
